<template>
  <ToolbarItemContainer ref="container" :iconFile="quickreplyIcon" title="快捷回复" :needBottomPopup="true"
    :iconWidth="isUniFrameWork ? '20px' : '20px'" :iconHeight="isUniFrameWork ? '20px' : '20px'" @click="openDrawer">
  </ToolbarItemContainer>
  <el-drawer v-model="drawer" :with-header="false" size="450px">
    <div class="drawer-header">
      <el-icon size="18" style="float: right; cursor: pointer;" @click="drawer = false">
        <CloseBold />
      </el-icon>
      <div class="title">快捷回复</div>
    </div>
    <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
      <el-tab-pane label="通用回复" name="first">
        <div style="display: flex; align-items: center;">
          <el-input v-model="key" style="width: 200px" size="small" placeholder="请输入关键词" />
          <el-button type="primary" size="small" style="margin-left: 10px" @click="handleSearch">搜索</el-button>
          <el-button size="small" style="margin-left: 10px" @click="handleClearSearch">重置</el-button>
        </div>
        <el-table :data="list" style="width: 100%">
          <el-table-column type="expand">
            <template #default="props">
              <div m="4">
                <p m="t-0 b-2">{{ props.row.content }}</p>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="标题" prop="title">
            <template #default="scope">
              <div m="t-0 b-2">{{ scope.row.title }}<span style="color: #f00;" v-if="scope.row.files">(包含附件)</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column width="100" label="操作">
            <template #default="scope">
              <el-button type="primary" size="small" @click="chooseReply(scope.row)">选择</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div style="display: flex; justify-content: center; align-items: center; margin-top: 10px;">
          <el-pagination size="small" background layout="prev, pager, next" :total="total" class="mt-4"
            @change="pageChange" />
          <div style="font-size: 12px; margin-left: 10px;">共{{ total }}条</div>
        </div>
      </el-tab-pane>
      <el-tab-pane label="自定义回复" name="second">
        <div style="display: flex; align-items: center;">
          <el-input v-model="key" style="width: 200px" size="small" placeholder="请输入关键词" />
          <el-button type="primary" size="small" style="margin-left: 10px" @click="handleSearch">搜索</el-button>
          <el-button size="small" style="margin-left: 10px" @click="handleClearSearch">重置</el-button>
          <el-button type="success" size="small" style="margin-left: 10px" @click="dialogVisible2 = true">添加</el-button>
        </div>
        <el-table :data="list" style="width: 100%">
          <el-table-column type="expand">
            <template #default="props">
              <div m="4">
                <p m="t-0 b-2">{{ props.row.content }}</p>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="标题" prop="title">
            <template #default="scope">
              <div m="t-0 b-2">{{ scope.row.title }}
              </div>
            </template>
          </el-table-column>
          <el-table-column width="140" align="center" label="操作">
            <template #default="scope">
              <el-button type="primary" size="small" @click="chooseReply(scope.row)">选择</el-button>
              <el-button type="danger" size="small" @click="delReply(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div style="display: flex; justify-content: center; align-items: center; margin-top: 10px;">
          <el-pagination size="small" background layout="prev, pager, next" :total="total" class="mt-4"
            @change="pageChange" />
          <div style="font-size: 12px; margin-left: 10px;">共{{ total }}条</div>
        </div>
      </el-tab-pane>
      <el-tab-pane label="知识库" name="third">
        <div style="display: flex; align-items: center;">
          <el-select v-model="first_cate" placeholder="请选择一级分类" size="small" @change="getFirstCate">
            <el-option v-for="item in cate" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
          <el-select v-model="second_cate" placeholder="请选择二级分类" size="small" style="margin-left: 10px"
            @change="getSecondCate">
            <el-option v-for="item in cate2" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </div>
        <div style="display: flex; align-items: center; margin-top: 10px;">
          <el-input v-model="key" style="width: 200px" size="small" placeholder="请输入关键词" />
          <el-button type="primary" size="small" style="margin-left: 10px" @click="handleSearch">搜索</el-button>
          <el-button size="small" style="margin-left: 10px" @click="handleClearSearch">重置</el-button>
        </div>
        <el-table :data="list" style="width: 100%">
          <el-table-column type="expand">
            <template #default="props">
              <div m="4">
                <p m="t-0 b-2">{{ props.row.content }}</p>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="标题" prop="title" />
          <el-table-column width="100" label="操作">
            <template #default="scope">
              <el-button type="primary" size="small" @click="chooseReply(scope.row)">选择</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div style="display: flex; justify-content: center; align-items: center; margin-top: 10px;">
          <el-pagination size="small" background layout="prev, pager, next" :total="total" class="mt-4"
            @change="pageChange" />
          <div style="font-size: 12px; margin-left: 10px;">共{{ total }}条</div>
        </div>
      </el-tab-pane>
    </el-tabs>
  </el-drawer>
  <el-dialog v-model="dialogVisible" title="发送话术" width="500">
    <el-input v-model="sendContent.content" style="width: 100%" :rows="5" type="textarea" placeholder="请输入发送内容" />
    <p style="color: #f00; margin: 5px 0; font-weight: bold;" v-if="sendContent.files">提示：（包含附件）</p>
    <el-image style="width: 120px; " :src="sendContent.files" :preview-src-list="[sendContent.files]" fit="cover"
      v-if="sendContent.files && sendContent.file_type == 1" />
    <a :href="sendContent.files" _blank="target" v-if="sendContent.file_type == 2" style="color: #666;">{{
      sendContent.file_name }}</a>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSendMsg">
          发送
        </el-button>
      </div>
    </template>
  </el-dialog>

  <el-dialog v-model="dialogVisible2" title="添加话术" width="500">
    <el-input v-model="addMsg.title" style="width: 100%; margin-bottom: 10px;" placeholder="请输入话术标题" />
    <el-input v-model="addMsg.content" style="width: 100%" :rows="5" type="textarea" placeholder="请输入话术内容" />
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible2 = false">取消</el-button>
        <el-button type="primary" :disabled="!addMsg.title || !addMsg.content" @click="handleAddMsg">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import TUIChatEngine, {
  TUIStore,
  StoreName,
  IConversationModel,
  TUIChatService,
  SendMessageParams,
  SendMessageOptions
} from '@tencentcloud/chat-uikit-engine';
import { ref, onMounted } from '../../../../adapter-vue';
import ToolbarItemContainer from '../toolbar-item-container/index.vue';
import quickreplyIconLight from '../../../../assets/icon/quickreply-light.svg';
import quickreplyIconDark from '../../../../assets/icon/quickreply-dark.svg';
import { isUniFrameWork } from '../../../../utils/env';
import TUIChatConfig from '../../config';
import type { TabsPaneContext } from 'element-plus'
import { getGeneralReply, addCustomReply, delCustomReply, getKnowledge, getKnowledgeCate } from '@/api';
import { isEnabledMessageReadReceiptGlobal } from '../../utils/utils';
import OfflinePushInfoManager, { IOfflinePushInfoCreateParams } from '../../offlinePushInfoManager/index';
import { sendMessages } from '../../utils/sendMessage';

const quickreplyIcon = TUIChatConfig.getTheme() === 'dark' ? quickreplyIconDark : quickreplyIconLight;

const container = ref();
const currentConversation = ref<IConversationModel>();

const drawer = ref(false);
const activeName = ref('first');
const list = ref([]);
const total = ref(0);
const params = {
  page: 1,
  keywords: '',
  type: 1,
  first_cate: 0,
  second_cate: 0
};
const key = ref('');
const dialogVisible = ref(false);
const sendContent = ref({});
const dialogVisible2 = ref(false);
const addMsg = ref({});
const cate = ref([]);
const cate2 = ref([]);
const first_cate = ref('');
const second_cate = ref('');

onMounted(() => {
  getKnowledgeCateList(0);
})

TUIStore.watch(StoreName.CONV, {
  currentConversation: (conversation: IConversationModel) => {
    currentConversation.value = conversation;
  },
});

function openDrawer() {
  drawer.value = true;
  activeName.value = 'first';
  params.type = 1;
  handleClearSearch();
}

const handleClick = (tab: TabsPaneContext) => {
  list.value = [];
  params.type = Number(tab.index) + 1;
  params.page = 1;
  params.keywords = '';
  key.value = '';
  getList();
}

function getList(){
  if (params.type < 3) {
    getReplyList();
  } else {
    getKnowledgeList();
  }
}

function handleClearSearch(){
  params.keywords = '';
  params.page = 1;
  params.first_cate = 0;
  params.second_cate = 0;
  key.value = '';
  first_cate.value = '';
  second_cate.value = '';
  cate2.value = [];
  getList();
}

function getReplyList() {
  getGeneralReply(params).then((res: any) => {
    list.value = res.data;
    total.value = res.count;
  })
}

function getKnowledgeList() {
  getKnowledge(params).then((res: any) => {
    list.value = res.data;
    total.value = res.count;
  })
}

function getKnowledgeCateList(pid :number) {
  getKnowledgeCate({
    pid: pid
  }).then((res: any) => {
    if (pid > 0) {
      cate2.value = res.data;
    } else {
      cate.value = res.data;
    }
  })
}

const pageChange = (e: number) => {
  params.page = e;
  getList();
};

function handleSearch() {
  params.keywords = key.value;
  params.page = 1;
  list.value = [];
  getList();
}

function chooseReply(row: any) {
  sendContent.value = row;
  dialogVisible.value = true;
}

function handleSendMsg() {
  if (params.type == 3) {
    sendTextMsg(sendContent.value.content);
  } else {
    if (sendContent.value.file_type == 0) {
      sendTextMsg(sendContent.value.content);
    }
    if (sendContent.value.file_type == 1) {
      let info = {
        businessID: 'imgMsg',
        type: 'imgMsg',
        desc: '',
        ext: `<p>${sendContent.value.content}</p>`,
        imageUrl: sendContent.value.files ? sendContent.value.files : '',
      };
      sendCustomMsg(info);
    }
    if (sendContent.value.file_type == 2) {
      sendTextMsg(sendContent.value.content);
      let info = {
        businessID: 'docMsg',
        type: 'docMsg',
        desc: sendContent.value.content,
        ext: '',
        name: sendContent.value.file_name ? sendContent.value.file_name : '',
        url: sendContent.value.files ? sendContent.value.files : '',
      };
      sendCustomMsg(info);
    }
  }
  drawer.value = false;
  dialogVisible.value = false;
}

function handleAddMsg() {
  if(addMsg.value.title == '' || addMsg.value.content == '') {
    return;
  }
  addCustomReply(addMsg.value).then(() => {
    addMsg.value.title = '';
    addMsg.value.content = '';
    dialogVisible2.value = false;
    getReplyList();
  })
}

function delReply(id :number) {
  delCustomReply({
    id: id
  }).then(() => {
    getReplyList();
  })
}

const getFirstCate = (value: any)  =>{
  params.first_cate = value;
  params.second_cate = 0;
  second_cate.value = '';
  getKnowledgeCateList(value);
}

const getSecondCate = (value: any) => {
  params.second_cate = value;
}
const sendTextMsg = (text :string) => {
  let info = [{
    payload: {
      text: text
    },
    type: 'text'
  }]
  sendMessages(
    info,
    currentConversation.value,
  );
}

const sendCustomMsg = (obj :object) => {
  const payload = {
    data: JSON.stringify(obj),
    description: '',
    extension: '',
  };
  const options = {
    to:
      currentConversation?.value?.groupProfile?.groupID
      || currentConversation?.value?.userProfile?.userID,
    conversationType: currentConversation?.value?.type,
    payload,
    needReadReceipt: isEnabledMessageReadReceiptGlobal(),
  };
  const offlinePushInfoCreateParams: IOfflinePushInfoCreateParams = {
    conversation: currentConversation.value,
    payload: options.payload,
    messageType: TUIChatEngine.TYPES.MSG_CUSTOM,
  };
  const sendMessageOptions: SendMessageOptions = {
    offlinePushInfo: OfflinePushInfoManager.create(offlinePushInfoCreateParams),
  };
  TUIChatService.sendCustomMessage(options as SendMessageParams, sendMessageOptions);
}
</script>

<style lang="scss" scoped>
    .drawer-header {
      padding: 20px 0;
  
      .title {
        font-size: 16px;
      }
    }
</style>